package com.witmore.neutron.ai.web.service.impl;

import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.db.entity.CooperationInquiryDO;
import com.witmore.neutron.ai.db.mapper.CooperationInquiryMapper;
import com.witmore.neutron.ai.web.controller.vo.CooperationInquirySubmitParam;
import com.witmore.neutron.ai.web.service.CooperationInquiryService;
import com.witmore.neutron.ai.web.service.WechatWorkNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 合作咨询服务实现类
 *
 * @author 豆子高
 * @since 2025-09-17
 */
@Slf4j
@Service
public class CooperationInquiryServiceImpl implements CooperationInquiryService {

    @Autowired
    private CooperationInquiryMapper cooperationInquiryMapper;

    @Autowired
    private WechatWorkNotifyService wechatWorkNotifyService;

    @Override
    public ResponseResult<Void> submitInquiry(CooperationInquirySubmitParam param) {
        try {
            // 创建合作咨询记录
            CooperationInquiryDO inquiryDO = new CooperationInquiryDO();
            BeanUtils.copyProperties(param, inquiryDO);
            inquiryDO.setStatus((byte) 0); // 待处理
            inquiryDO.setWechatSent((byte) 0); // 未发送
            inquiryDO.setCreateTime(LocalDateTime.now());

            // 保存到数据库
            cooperationInquiryMapper.insert(inquiryDO);

            // 异步发送企业微信通知
            try {
                wechatWorkNotifyService.sendCooperationInquiryNotify(inquiryDO);
                // 更新发送状态
                inquiryDO.setWechatSent((byte) 1);
                inquiryDO.setWechatSentTime(LocalDateTime.now());
                cooperationInquiryMapper.updateById(inquiryDO);
            } catch (Exception e) {
                log.error("发送企业微信通知失败", e);
                inquiryDO.setWechatSent((byte) 2);
                inquiryDO.setHandleNotes(e.getMessage());
                cooperationInquiryMapper.updateById(inquiryDO);
            }

            return ResponseResult.success();

        } catch (Exception e) {
            log.error("提交合作咨询失败", e);
            return ResponseResult.fail(500, "提交失败，请稍后重试");
        }
    }

}
